package jam.network;   
         
import jam.ClientApplication;
import jam.model.ClientModel;                                    
import jam.network.message.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.HashMap;

/**
 * Controller that does the client's network handling.
 */
public class NetworkController { 

	private Socket socket;
	private ClientModel clientModel;
	private static final int PORT = 7777;
	private static final String  HOST = "bo720-3-06";

	Scanner in = null;
    static PrintWriter out = null;                                          
	private static int transID = 0;

	//hashmap to store every sent message, indexed by its transID
	public static HashMap<Integer, String> sent = new HashMap<Integer, String>();

	/** 
	 * Constructor.
	 */
    public NetworkController(ClientModel clientModel) {
        //set up socket
		try{
            socket = new Socket( HOST, PORT);
			System.out.println("Connected to host: " + HOST);
		} catch (IOException e){
			System.err.println("Can't connect to host: " + HOST);
			System.exit( 1 ); 
        }
		//set up socket I/O
		try {
			in = new Scanner( new BufferedReader( new InputStreamReader( socket.getInputStream())));
			out = new PrintWriter( socket.getOutputStream(), true);
		}  catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + HOST);
            System.exit( 1 );
        }

		this.clientModel = clientModel;
	}

	//getters and setters//
	public static int getTransID() {
		return transID;
	}

	public static void setTransID() {
		transID++;
	}

	/**
	 * Method to send String messages to server
	 */
	public static void send(String message) {
		out.println(message);	
	}

	/**
	 * Listens for messages from the server.
	 */
	public void run() {
		//tests
		/*		
		ClientActionLogin logintest = new ClientActionLogin( "i91scott@gmail.com", "blahblah");
		send(logintest.toString());
		ClientActionJoinChannel jointest = new ClientActionJoinChannel("#teamk");
		send(jointest.toString());
		ClientRequestUserList userltest = new ClientRequestUserList("#teamk");
		send(userltest.toString());
		ClientActionMessage msgtest = new ClientActionMessage("#teamk", "This is a test mang, better work yo.");
		send(msgtest.toString());
		*/
		
		while (socket.isClosed() == false) {
			if (in.hasNextLine()) {
				MessageParser.parseMessage(in.nextLine(), clientModel);
			}
		}
	}
}

